﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using KeXin.IService;
using KeXin.Model.Config;
using KeXin.Model.DTO;
using KeXin.Model.Input;
using KeXin.Model.Output;
using Microsoft.AspNetCore.Http;

namespace KeXin.Service
{
    public class AdminService:BaseService,IAdminService
    {
        private readonly IFreeSql _fsql;
        private readonly IHttpContextAccessor _accessor;

        public AdminService(IFreeSql iFreeSql, IHttpContextAccessor accessor)
        {
            _fsql = iFreeSql;
            _accessor = accessor;
        }

        public async Task<PageOutput<AdminDTO>> GetPageListAsync(AdminInput input)
        {
           var list= await _fsql.Select<Entity.SysAdmin>()
                .WhereIf(!string.IsNullOrEmpty(input.LoginName), p => p.LoginName.Contains(input.LoginName))
                .WhereIf(!string.IsNullOrEmpty(input.RealName), p => p.RealName.Contains(input.RealName))
                .OrderBy(p => p.Sort)
                .OrderBy(p => p.ID)
                .Count(out var recordCount)
                .Page(input.PageIndex, input.PageSize)
                .ToListAsync(p=>new AdminDTO(){});

           return new PageOutput<AdminDTO> { List = list, Total = recordCount };
        }

        public async Task<AdminOutput> GetInfoAsync(long id)
        {
            return  await _fsql.Select<Entity.SysAdmin>().Where(p => p.ID == id).ToOneAsync(p => new AdminOutput());
        }

        /// <summary>
        /// 获取token值示例，获取用户id
        /// </summary>
        /// <returns></returns>
        public long GetAdminIDByToken()
        {
            var token = _accessor.HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
            JwtSecurityToken jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
            return Convert.ToInt64(jwtToken.Payload[ClaimName.AdminId].ToString());
        }

    }
}
